<template>
  <div>
    <van-pull-refresh v-model="isLoading" success-text="刷新成功" @refresh="onRefresh" >
      <!-- 搜索 -->
      <van-search v-model="this.queryInfo.query" placeholder="请输入搜索关键词" @search="onSearch" />
      <!-- to 属性是路由跳转 --> 
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-card
          :price="item.goodsPrice"
          :title="item.goodsName"
          :thumb="item.goodsCoverImg"
          v-for="item in goodsList"
          :key="item.goodsId"
          @click="goodsInfo(item.goodsId)"
        >
          <template #tags v-if="item.tags.length !== 0">
            <van-tag plain type="danger" v-for="tag in item.tags" :key="tag.tagId">{{tag.tagName}}</van-tag>
          </template>
        </van-card>      
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
export default {
  data() {
    return {
      goodsList: [],
      queryInfo: {
        query: '',
        //当前页数
        pagenum: 1,
        //当前每页显示多少数据
        pagesize: 10
      },
      total: '',
      loading: false,
      finished: false,
      isLoading: false
    }
  },
  methods: {
    async getGoodsList() {
      //获取商品列表
      const {data: res } =await this.$http.post('/api/goods/getAllGoodsForUser',{query:this.queryInfo.query, pagenum:this.queryInfo.pagenum, pagesize: this.queryInfo.pagesize})
      if (res.code !== 200) {
        this.$toast('论坛加载失败')
        return
      }
      if (res.data.records.length === 0) {  		// 判断获取数据条数若等于0
        this.finished = true;		// 停止加载
      }
      //数据不为0
      this.goodsList.push(...res.data.records)//加载数据
      this.total = res.data.total //给数据条数赋值
      this.loading = false			// 加载状态结束 
      // 如果list长度大于等于总数据条数,数据全部加载完成
      if (this.goodsList.length >= res.data.total) {
          this.finished = true	// 结束加载状态
      }
    },
    onLoad() {
      this.getGoodsList()
      this.queryInfo.pagenum++
    },
    onSearch() {
      this.queryInfo.pagenum = 1 //设置查询页数为1
      this.goodsList = [] //置空商品列表
      this.finished = false //重置加载状态
      this.onLoad()
    },
    goodsInfo(id) {
      this.$router.push({name: 'goodsInfo',params: {goodsId: id}})
    },
    onRefresh() {
      this.queryInfo.pagenum = 1
      this.onLoad()
      this.goodsList = []
      this.$toast('刷新成功')
      this.finished = false
      this.isLoading = false
    }
  }

}
</script>

<style lang="less" scoped>
.van-pull-refresh {
  height: 800px;
}
</style>